package org.inspursc.s0517.health.evaluation.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.*;
import io.swagger.models.auth.In;
import org.inspursc.s0517.health.evaluation.dto.*;
import org.inspursc.s0517.health.evaluation.entity.AnRadio;
import org.inspursc.s0517.health.evaluation.enums.AppraiseStutasEnum;
import org.inspursc.s0517.health.evaluation.enums.SuggestByScoreEnum;
import org.inspursc.s0517.health.evaluation.service.*;
import org.inspursc.s0517.health.evaluation.utils.DataTypeUtil;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author B_Dream
 * @version ：2018/7/9 14:54
 */

public class OneSurveyAppraiseServiceImpl implements SurveyAppraiseService {


    @Override
    public Map<String, Object> appraise(Multimap<String, AnRadioDTO> anRadioMultimap, CustomerDTO customer, List<QuestionCategoryDTO> categoryDTOS) {

        //获取分类ID名字
        Map<Integer, String> cateNameMap = Maps.newHashMap();
        for (QuestionCategoryDTO categoryDTO : categoryDTOS) {
            cateNameMap.put(categoryDTO.getId(), categoryDTO.getName());
        }

        //认知能力
        Integer d020 = anRadioMultimap.get(SuggestByScoreEnum.PERCEIVE.getCode()).stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        //行动能力
        int e007 = 0;
        int e003 = 0;
        for (AnRadioDTO e : anRadioMultimap.get(SuggestByScoreEnum.DAILYLIFE.getCode())) {
            if ("E003".equals(e.getQuestionItem())) {
                e003 = e.getOptionScore();
            }
            if ("E007".equals(e.getQuestionItem()) || "E008".equals(e.getQuestionItem()) || "E009".equals(e.getQuestionItem())) {
                e007 += e.getOptionScore();
            }
        }

        //一级分类相同集合
        Multimap<String, SecondCategoryKpiDTO> secondCateKpiMap = ArrayListMultimap.create();
        Multimap<Integer, SecondCategoryKpiDTO> fristIdMultiMap = ArrayListMultimap.create();

        //自动计算结果map
        Map<String,String> antoMap=Maps.newHashMap();
        //一级目录二级目录相同的分类评分组装
        for (String dto : anRadioMultimap.keySet()) {
            Integer firstInt = Integer.parseInt(dto.substring(0, dto.lastIndexOf("-")));
            List<AnRadioDTO> anRadios = ((ArrayListMultimap<String, AnRadioDTO>) anRadioMultimap).get(dto);
            SecondCategoryKpiDTO secondCategoryKpiDTO = this.getSuggestByScore(dto, anRadios, customer, d020, e007, e003);
            String cataName=cateNameMap.get(Integer.parseInt(dto.substring(dto.lastIndexOf("-") + 1)));
            secondCategoryKpiDTO.setName(cataName);
            secondCateKpiMap.put(dto, secondCategoryKpiDTO);
            fristIdMultiMap.put(firstInt, secondCategoryKpiDTO);
            if(secondCategoryKpiDTO.getAntoCompute()!=null) {
                antoMap.put("<strong>" + cataName + "</strong>", secondCategoryKpiDTO.getAntoCompute() );
            }
        }


        //一级分类相同评分结果组装
        List<CategoryKpiDTO> list = Lists.newArrayList();

        for (Integer firstInt : fristIdMultiMap.keySet()) {

            //该分类下的所有二级分类
            List<SecondCategoryKpiDTO> secondCategoryKpiDTO = ((ArrayListMultimap<Integer, SecondCategoryKpiDTO>) fristIdMultiMap).get(firstInt);
            Double totalScore = secondCategoryKpiDTO.stream().mapToDouble(SecondCategoryKpiDTO::getScore).sum();

            List<String> stateStr = secondCategoryKpiDTO.parallelStream().map(SecondCategoryKpiDTO::getStatus).collect(Collectors.toList());
            StringBuilder sbDesc = new StringBuilder();

            for (SecondCategoryKpiDTO dto : secondCategoryKpiDTO) {
                stateStr.add(dto.getStatus());
                sbDesc.append(dto.getDescription() + "<br/>");
            }

            String status = this.getStateStr(stateStr);
            CategoryKpiDTO categoryKpiDTO = new CategoryKpiDTO();
            if (4 == firstInt) {

                Double atheartScore = secondCateKpiMap.get(SuggestByScoreEnum.ATHEART.getCode()).stream().mapToDouble(SecondCategoryKpiDTO::getScore).sum();
                Double perceiveScore = secondCateKpiMap.get(SuggestByScoreEnum.PERCEIVE.getCode()).stream().mapToDouble(SecondCategoryKpiDTO::getScore).sum();
                totalScore = atheartScore * 1.2 + perceiveScore * 1.5;

                categoryKpiDTO.setSecondCategoryKpi(secondCategoryKpiDTO);
                categoryKpiDTO.setScore(DataTypeUtil.doubleFormatTwo(totalScore));
                categoryKpiDTO.setName(cateNameMap.get(firstInt));
                categoryKpiDTO.setDescription(" ");
                categoryKpiDTO.setStatus(status);
                list.add(categoryKpiDTO);

            } else if (2 == firstInt) {
                double medical = secondCateKpiMap.get(SuggestByScoreEnum.MEDICAL.getCode()).stream().mapToDouble(SecondCategoryKpiDTO::getScore).sum();
                totalScore = totalScore - medical;
                categoryKpiDTO.setSecondCategoryKpi(secondCategoryKpiDTO);
                categoryKpiDTO.setScore(DataTypeUtil.doubleFormatTwo(totalScore));
                categoryKpiDTO.setName(cateNameMap.get(firstInt));
                categoryKpiDTO.setDescription(" ");
                categoryKpiDTO.setStatus(status);
                list.add(categoryKpiDTO);

            } else {
                categoryKpiDTO.setSecondCategoryKpi(secondCategoryKpiDTO);
                categoryKpiDTO.setScore(DataTypeUtil.doubleFormatTwo(totalScore));
                categoryKpiDTO.setName(cateNameMap.get(firstInt));
                categoryKpiDTO.setDescription(" ");
                categoryKpiDTO.setStatus(status);
                list.add(categoryKpiDTO);

            }
        }

        Double total = list.stream().mapToDouble(CategoryKpiDTO::getScore).sum();

        String conclu = this.getConclusionByTotalScore(total);
        Map<String, Object> map = Maps.newHashMap();
        map.put("categoryKpi", list);
        map.put("total_score", DataTypeUtil.getInt(total));
        map.put("description", conclu);
        JSON antoJson=JSON.parseObject(JSON.toJSONString(antoMap));
        map.put("anto_map",antoJson);
        return map;
    }

    private String getConclusionByTotalScore(Double total) {
        String conclu = "评测结论：";
        if (total != null) {
            if (total >= 85 && total <= 100) {
                conclu += "该被评测人为健康的老年人。";
            } else if (total >= 70) {
                conclu += "该被评测人为轻度失能的老年人。";
            } else if (55 <= total) {
                conclu += "该被评测人为中度失能的老年人。";
            } else if (0 <= total) {
                conclu += "该被评测人为重度失能的老年人。";
            } else {
                conclu += "该评测异常。";
            }
            return conclu;
        } else {
            return null;
        }
    }


    private String getStateStr(List<String> stateStr) {
        if (stateStr.contains(AppraiseStutasEnum.SERIOUS.getName())) {
            return AppraiseStutasEnum.SERIOUS.getName();
        } else if (stateStr.contains(AppraiseStutasEnum.WARN.getName())) {
            return AppraiseStutasEnum.WARN.getName();
        } else {
            return AppraiseStutasEnum.NORMAL.getName();
        }
    }


    /**
     * 根据年龄获取相应得分
     * @param
     * @return
     */
    private Integer getAgeScore(Integer age) {
        Integer score = 0;
        if (age != null) {
            if (age < 40) {
                score = 0;
            } else if (age >= 40 && age <= 50) {
                score = 1;
            } else if (age >= 51 && age <= 60) {
                score = 2;
            } else if (age >= 61 && age <= 70) {
                score = 3;
            } else if (age > 71 && age < 80) {
                score = 4;
            }
        } else {
            score = 4;
        }
        return score;
    }


    private SecondCategoryKpiDTO getSuggestByScore(String cateId, List<AnRadioDTO> anRadios, CustomerDTO customer, Integer d020, Integer e007, Integer e003) {

        switch (cateId) {
            case "2-3":
                return this.getMedicalCate(anRadios, customer);
            case "2-13":
                return this.getPainCate(anRadios);
            case "2-14":
                return this.getNutitureCate(anRadios, customer, d020, e007);
            case "2-15":
                return this.getSleepCate(anRadios);
            case "4-8":
                return this.getAtheartCate(anRadios);
            case "4-9":
                return this.getPerceiveCate(anRadios);
            case "5-10":
                return this.getDailylifeCate(anRadios);
            case "5-12":
                return this.getTumbleCate(anRadios, customer, d020, e007, e003);
            case "6-16":
                return this.getApperceiveCate(anRadios);
            case "7-17":
                return this.getSocialCate(anRadios);
            default:
                return null;
        }
    }



    //二、1．既往病史
    private SecondCategoryKpiDTO getMedicalCate(List<AnRadioDTO> anRadios, CustomerDTO customer) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();
        Integer totalScore;
       StringBuilder antoSb=new StringBuilder();
        //描述
        String desc;
        AppraiseStutasEnum stutas;
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();

        //自动计算，B003a+B003b+……+B003o
        List<AnRadioDTO> radioList = anRadios.stream().filter(e -> e.getQuestionItem().substring(0, 4).equals("B003")).collect(Collectors.toList());
//      Integer total = anRadios.stream().filter(anRadio -> anRadio.getQuestionItem().substring(0, 4).equals("B003")).mapToInt(AnRadioDTO::getOptionScore).sum();

        Integer b003z = 0;
        for (AnRadioDTO radio : radioList) {
            b003z += radio.getOptionScore();
            if (radio.getOptionScore() > 0) {
                markAnRadio.add(radio);
            }
        }

        Integer age = customer.getAge();
        Integer ageScore=this.getAgeScore(age);
        antoSb.append("年龄:为"+age+",年龄计算得分："+ageScore+"分。</br>");

        //自动计算，B003a+B003b+……+B003p
        Integer b003z1 = b003z + ageScore;
        Integer b001 = anRadios.stream().filter(anRadio -> anRadio.getQuestionItem().substring(0, 4).equals("B001")).mapToInt(AnRadioDTO::getOptionScore).sum();
        Integer b002 = anRadios.stream().filter(anRadio -> anRadio.getQuestionItem().substring(0, 4).equals("B002")).mapToInt(AnRadioDTO::getOptionScore).sum();;

        totalScore = b003z1 + b001 + b002;
        if (totalScore <= 7 && b003z1 == 0) {
            desc = "健康状况良好，普通慢性病、轻症，需定时评估、体检；";
            stutas = AppraiseStutasEnum.NORMAL;
        } else if (totalScore <= 7 && b003z1 > 0) {
            desc = "有重大疾病隐患，建议及时前往医疗机构检查及治疗；";
            stutas = AppraiseStutasEnum.WARN;
        } else if (totalScore >= 8 && totalScore <= 34) {
            desc = "健康状况较差，有一至多种常见重大疾病隐患，建议及时入院治疗。";
            stutas = AppraiseStutasEnum.SERIOUS;
        } else {
            desc = "数据异常,请联系管理员";
            stutas = AppraiseStutasEnum.OTHER;
        }

        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        dto.setAntoCompute(antoSb.toString());
        return dto;
    }


    //二、2．疼痛评测
    private SecondCategoryKpiDTO getPainCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();
        double totalScore;
        //描述
        String desc;
        AppraiseStutasEnum stutas;
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();

        totalScore = (double) anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        if (totalScore == 0) {
            desc = "重度疼痛，严重影响睡眠，建议应及时前往医疗机构检查或就医；";
            stutas = AppraiseStutasEnum.SERIOUS;
        } else if (totalScore >= 1 && totalScore <= 3) {
            desc = "中度疼痛，睡眠受影响，建议应及时前往医疗机构检查或就医；";
            stutas = AppraiseStutasEnum.WARN;
        } else if (totalScore >= 4 && totalScore <= 6) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "轻度疼痛，睡眠不受影响，应时常观测，找出疼痛原因，及时前往医疗机构检查；";
        } else if (totalScore >= 7 && totalScore <= 10) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "无痛，睡眠不受影响。";
        } else {
            desc = "数据异常,请联系管理员";
            stutas = AppraiseStutasEnum.OTHER;
        }


        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }

    private Integer getScoreByBMI(Integer heigt, Integer weight) {
        Integer score = 0;
        Double _height = (double)heigt / 100;
       double  BMI = ((double) weight) / (_height * _height);
        if (BMI < 19) {
            score = 0;
        } else if (BMI >= 19 && BMI < 21) {
            score = 1;
        } else if (BMI >= 21 && BMI < 23) {
            score = 2;
        } else if (BMI >= 23) {
            score = 3;
        }
        return score;

    }

    // 二、3．营养状况
    private SecondCategoryKpiDTO getNutitureCate(List<AnRadioDTO> anRadios, CustomerDTO customer, Integer d020, Integer e007) {
        double totalScore;

        StringBuilder antoCmpDesc=new StringBuilder();

        Integer I006a = 0;
        if(customer.getHeight()==null||customer.getWeight()==null){
            I006a=2;
            antoCmpDesc.append("身高或体重数据为空，所以身高和体重被默认。"+"BMI评测项计算得分：2分。</br>");
        }else {
            I006a=  this.getScoreByBMI(customer.getHeight(),customer.getWeight());
            antoCmpDesc.append("身高为"+customer.getHeight()+"，体重为"+customer.getWeight()+"，BMI评测项计算得分："+I006a+"分。</br>");
        }

        Integer I003 = 0;
        Integer I005 = 0;

        String descs=null;
        if (e007 == 12) {
            //2=可以外出
            I003 = 2;
            descs="可以外出";
        } else if (e007>3&&e007 < 12) {
            //1=可以下床或离开轮椅，但不能外出
            I003 = 1;
            descs="可以下床或离开轮椅，但不能外出";
        } else {
            //0=需长期卧床或坐轮椅
            I003 = 0;
            descs="需长期卧床或坐轮椅";

        }
        antoCmpDesc.append("活动能力：计算得分："+I003+"分（"+descs+"）。</br>");

        if (0 <= d020 && d020 <= 15) {
            //0=严重痴呆或抑郁
            I005 = 0;
            descs="严重痴呆或抑郁";
        } else if (16 <= d020 && d020 <= 24) {
            // 1=轻度痴呆
            I005 = 1;
            descs="轻度痴呆";
        } else if (25 <= d020 && d020 <= 30) {
            //2=没有精神心理问题
            I005 = 2;
            descs="没有精神心理问题";
        }
        antoCmpDesc.append("精神心理问题：计算得分："+I005+"分（"+descs+"）。</br>");

        totalScore = I003 + I005 + I006a;
        for (AnRadioDTO dto : anRadios) {
            if ("I001".equals(dto.getQuestionItem()) || "I002".equals(dto.getQuestionItem()) || "I004".equals(dto.getQuestionItem())) {
                totalScore += dto.getOptionScore();
            }
        }

        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();
        //描述
        String desc;
        AppraiseStutasEnum stutas;
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();

        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 0 || radio.getOptionScore() == 1) {
                markAnRadio.add(radio);
            }
        }

        // totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        if (totalScore >= 0 && totalScore <= 7) {
            desc = "营养不良，建议应及时前往医疗机构检查或就医；";
            stutas = AppraiseStutasEnum.SERIOUS;
        } else if (totalScore >= 8 && totalScore <= 11) {
            desc = "有营养不良风险，建议从膳食和营养搭配等方面加强；";
            stutas = AppraiseStutasEnum.WARN;
        } else if (totalScore >= 12 && totalScore <= 14) {
            desc = "正常营养状况。";
            stutas = AppraiseStutasEnum.NORMAL;
        } else {
            desc = "数据异常,请联系管理员";
            stutas = AppraiseStutasEnum.OTHER;
        }
        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        dto.setAntoCompute(antoCmpDesc.toString());
        return dto;
    }

    //二、4．睡眠评估
    private SecondCategoryKpiDTO getSleepCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();
        double totalScore;
        //描述
        String desc;
        AppraiseStutasEnum stutas;
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();
        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 0) {
                markAnRadio.add(radio);
            }
        }
        totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        if (totalScore >= 0 && totalScore <= 4) {
            stutas = AppraiseStutasEnum.SERIOUS;

            desc = "睡眠质量等级非常差，存在入睡时间过长或睡眠维持时间过短等情况；";
        } else if (totalScore >= 5 && totalScore <= 8) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "睡眠质量等级中级，重点关注老年人是否借助安眠药物帮助睡眠；";
        } else if (totalScore >= 9 && totalScore <= 11) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "正常睡眠质量等级。";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }

        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }

    //三、1．心理健康
    private SecondCategoryKpiDTO getAtheartCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();
        double totalScore;
        //描述
        String desc;
        AppraiseStutasEnum stutas;

        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();

        totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 2) {
                markAnRadio.add(radio);
            } else if (radio.getOptionScore() == 3 || radio.getOptionScore() == 4) {
                induce.add(radio);
            }
        }

        if (totalScore >= 20 && totalScore <= 33) {
            stutas = AppraiseStutasEnum.SERIOUS;
            desc = "有较严重的心理疾病风险，建议应及时前往心理医疗机构就诊；";
        } else if (totalScore >= 34 && totalScore <= 44) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "有轻度心理疾病风险或有轻度心理障碍，建议可寻求心理咨询和疏导；";
        } else if (totalScore >= 45 && totalScore <= 60) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "心理非常健康，需进一步保持。";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }

        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }

    //三、2．认知能力
    private SecondCategoryKpiDTO getPerceiveCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();
        double totalScore;
        String desc;
        AppraiseStutasEnum stutas;
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();
        //计算总分
        totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        //记录D013分
        Integer tmpScore = 0;
        //D001是否回答正确
        boolean isRight = true;
        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 0) {
                markAnRadio.add(radio);
            }
            if ("D011".equals(radio.getQuestionItem())) {
                if (radio.getOptionScore() == 0) {
                    isRight = false;
                }
            }
            if ("D013".equals(radio.getQuestionItem())) {
                tmpScore = radio.getOptionScore();
            }
        }
        if (!isRight) {
            totalScore = totalScore - tmpScore;
        }
        if (totalScore >= 0 && totalScore <= 15) {
            stutas = AppraiseStutasEnum.SERIOUS;
            desc = "严重认知功能障碍，存在痴呆风险；";
        } else if (totalScore >= 16 && totalScore <= 24) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "轻度认知功能障碍，或患有轻微老年认知障碍风险；";
        } else if (totalScore >= 25 && totalScore <= 30) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "没有认知功能障碍。";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }

        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }

    //四、1.日常生活能力
    private SecondCategoryKpiDTO getDailylifeCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();

        double totalScore;

        //描述
        String desc;
        AppraiseStutasEnum stutas;

        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();

        totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 1) {
                markAnRadio.add(radio);
            } else if (radio.getOptionScore() == 2) {
                induce.add(radio);
            }
        }

        if (totalScore >= 19 && totalScore <= 30) {
            stutas = AppraiseStutasEnum.SERIOUS;
            desc = "重度依赖，生活能力严重缺失，全部需要他人照护；";
        } else if (totalScore >= 31 && totalScore <= 44) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "中度依赖，生活能力较差，大部分需要他人照护；";
        } else if (totalScore >= 45 && totalScore <= 57) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "轻度依赖，生活能力基本自理，少部分需要他人照护；";
        } else if (totalScore >= 58 && totalScore <= 76) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "无需依赖，生活完全自理，无需他人照护；";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }

        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }

    //todo  四、2.平衡能力

    // 四、3．跌倒风险
    private SecondCategoryKpiDTO getTumbleCate(List<AnRadioDTO> anRadios, CustomerDTO customer, Integer d020, Integer d007, Integer e003) {


        double totalScore;
        StringBuilder antoComDesc=new StringBuilder();

        // G001 0=80岁以上 1=76-80岁 2=65-75岁 4=64岁以下
        // Integer g001 = this.getAgeScore(customer.getAge());
        Integer g001 = 0;
        if(customer.getAge() != null && customer.getAge() <= 64){
            g001 = 4;
            antoComDesc.append("年龄得分：4</br>");
        } else if (customer.getAge() != null && customer.getAge() <= 75) {
            g001 = 2;
            antoComDesc.append("年龄得分：2</br>");
        } else if(customer.getAge() != null && customer.getAge() <= 80) {
            g001 = 1;
            antoComDesc.append("年龄得分：1</br>");
        } else if(customer.getAge() != null && customer.getAge() > 80){
            g001 = 0;
            antoComDesc.append("年龄得分：0</br>");
        } else {
            antoComDesc.append("年龄数据异常， 无法计算年龄得分。</br>");
        }

        Integer g002 = 0;
        Integer g003;
        Integer g004=0;


        String descs=null;
        if (0 <= d020 && d020 <= 24) {
            g002 = 0;
            descs="认知障碍";
        } else if (0 <= d020 && d020 <= 30) {
            g002 = 1;
            descs="认知正常";
        }
        antoComDesc.append("认知能力：计算得分:"+g002+"分（"+descs+"）。</br>");
        //G003 行动能力


        if (d007 == 12) {
            g003 = 1;
            descs="行动正常";
        } else {
            g003 = 0;
            descs="行动障碍";
        }

        antoComDesc.append("行动能力：计算得分:"+g003+"分（"+descs+"）。</br>");


        // G004 自理程度-排泄

        if (e003 == 4) {
            g004 = 1;
            descs="失禁或需要别人帮助";
        } else {
            descs ="能独立如厕";
        }
        antoComDesc.append("自理程度：计算得分:"+g004+"分（"+descs+"）。</br>");

        totalScore = g001 + g002 + g003 + g004;


        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();

        //描述
        String desc;
        AppraiseStutasEnum stutas;
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();


        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 0) {
                markAnRadio.add(radio);
            }
            if ("G005".equals(radio.getQuestionItem()) || "G006".equals(radio.getQuestionItem())) {
                totalScore += radio.getOptionScore();
            }
        }

        if (totalScore >= 0 && totalScore <= 2) {
            stutas = AppraiseStutasEnum.SERIOUS;
            desc = "高危风险，时常发生跌倒，需要专人照护；";
        } else if (totalScore >= 3 && totalScore <= 5) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "中度风险，偶尔发生跌倒，应做好跌倒防护和处理措施；";
        } else if (totalScore >= 6 && totalScore <= 9) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "低危风险，难免会发生跌倒，应做好跌倒防护和处理措施；";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }

        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        dto.setAntoCompute(antoComDesc.toString());
        return dto;
    }


    //五.感知感觉能力
    private SecondCategoryKpiDTO getApperceiveCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();

        double totalScore;

        //描述
        String desc;
        AppraiseStutasEnum stutas;
        //标注
        StringBuilder marking = new StringBuilder();
        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();


        totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();

        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 1 || radio.getOptionScore() == 2) {
                markAnRadio.add(radio);
            }
        }
        if (totalScore >= 10 && totalScore <= 16) {
            stutas = AppraiseStutasEnum.SERIOUS;
            desc = "感知觉能力等级非常低，感知觉能力退化严重；";
        } else if (totalScore >= 17 && totalScore <= 28) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "感知觉能力等级中级，感知觉能力部分退化，需加强预防性练习和防护；";
        } else if (totalScore >= 29 && totalScore <= 40) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "感知觉能力等级正常。";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }


        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }


    //六.社会参与
    private SecondCategoryKpiDTO getSocialCate(List<AnRadioDTO> anRadios) {
        SecondCategoryKpiDTO dto = new SecondCategoryKpiDTO();

        double totalScore;

        //描述
        String desc;
        AppraiseStutasEnum stutas;
        //标注

        List<AnRadioDTO> markAnRadio = Lists.newArrayList();
        List<AnRadioDTO> induce = Lists.newArrayList();

        totalScore = anRadios.stream().mapToInt(AnRadioDTO::getOptionScore).sum();
        for (AnRadioDTO radio : anRadios) {
            if (radio.getOptionScore() == 0 || radio.getOptionScore() == 1) {
                markAnRadio.add(radio);
            }
        }
        if (totalScore >= 0 && totalScore <= 8) {
            stutas = AppraiseStutasEnum.SERIOUS;
            desc = "社会参与能力等级非常低，孤独感强，几乎不能获得亲属、朋友等帮助和支持；";
        } else if (totalScore >= 9 && totalScore <= 18) {
            stutas = AppraiseStutasEnum.WARN;
            desc = "社会参与能力等级中级，与部分亲属、朋友或邻居关系较差，团体融入较差；";
        } else if (totalScore >= 19 && totalScore <= 28) {
            stutas = AppraiseStutasEnum.NORMAL;
            desc = "社会参与能力等级正常，亲属、朋友和邻居关系和谐，能得到部分帮助和支持。";
        } else {
            stutas = AppraiseStutasEnum.OTHER;
            desc = "数据异常,请联系管理员";
        }


        dto.setScore(DataTypeUtil.doubleFormat(totalScore));
        dto.setDescription(getDescription(markAnRadio, induce, desc));
        dto.setStatus(stutas.getName());
        return dto;
    }

    private String getDescription(List<AnRadioDTO> markAnRadio, List<AnRadioDTO> induce, String desc) {
        StringBuilder marking = new StringBuilder();
        if (markAnRadio != null && markAnRadio.size() > 0) {
            marking.append("<span style=\"color:red\">【重点标注问题】：</span><br/>");
            for (AnRadioDTO anRadioDTO : markAnRadio) {
                marking.append("问题：" + anRadioDTO.getQuestionName() + "&nbsp回答结果：" + anRadioDTO.getOptionAnswer() + "<br/>");
            }
        }

        if (induce != null && induce.size() > 0) {
            marking.append("<span style=\"color:orange\">【应该注意问题】：</span><br/>");
            for (AnRadioDTO anRadioDTO : induce) {
                marking.append("问题：" + anRadioDTO.getQuestionName() + "&nbsp回答结果：" + anRadioDTO.getOptionAnswer() + " <br/>");
            }
        }

        return "<span style=\"color:green\">【评测结论】：</span><br/>" + desc + "<br/>" + marking.toString();
    }



}
